package com.lipuwater.agent.ble.control;

import android.content.Context;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;

import com.blekit.Code;
import com.blekit.Constants;
import com.blekit.model.BleGattProfile;
import com.lipuwater.agent.ble.DeviceConn;
import com.lipuwater.agent.ble.DeviceNotice;
import com.lipuwater.agent.ble.DeviceWrite;
import com.lipuwater.agent.ble.command.DeviceCommand20;
import com.lipuwater.agent.ble.listener.ConnListener;
import com.lipuwater.agent.ble.listener.NoticeListener;
import com.lipuwater.agent.ble.utils.ByteParsing;
import com.lipuwater.agent.ble.utils.ByteUtils;
import com.lipuwater.agent.ui.dialog.LoadingDialog;
import com.lipuwater.agent.utils.link.CompleteInterface;
import com.lipuwater.agent.utils.link.ErrorInterface;
import com.lipuwater.agent.utils.link.LinkCallTask;
import com.lipuwater.agent.utils.link.NextInterface;
import com.ismartlib.utils.L;

/**
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃永无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * Created by  Administrator  on 2017/3/6.
 * Email:924686754@qq.com
 * 重置设备滤芯
 */
public class DeviceResetFilterControl implements NoticeListener {
    private Context mContext;
    private int mResetLevel = 0;//复位几级滤芯
    private DeviceConn mDeviceConn;
    private DeviceWrite mDeviceWrite;
    private DeviceNotice mDeviceNotice;
    private String mMac;
    private Handler mHandler;
    private int sameTimeOut = 5000;
    private LoadingDialog mLoading = null;
    private LinkCallTask mLinkCallTask = null;
    private boolean mRinse;
    private int stopTime = 500;

    public DeviceResetFilterControl(Context mContext, String mDeviceMac, int resetLevel, boolean rinse) {
        this.mContext = mContext;
        this.mMac = mDeviceMac;
        this.mRinse = rinse;
        this.mResetLevel = resetLevel;
        mLinkCallTask = new LinkCallTask();
        if (mRinse) {
            //单独只要反冲洗
            rinseSteps();
        } else {
            ResetFilterSteps();
        }
        init();
    }

    private void init() {
        mDeviceConn = new DeviceConn();
        if (mDeviceConn.getConnState(mMac) == Constants.STATUS_DEVICE_CONNECTED) {
            //已经连接
            start();
        } else {
            //没有连接
            connDev();
        }
    }

    private void start() {
        if (mRinse) {
            mLoading = new LoadingDialog(mContext, "冲洗中...");
        } else {
            mLoading = new LoadingDialog(mContext, "重置中...");
        }
        mLoading.showDialog();
        mDeviceWrite = new DeviceWrite();
        mDeviceNotice = new DeviceNotice();
        mDeviceNotice.Notify(mMac, this);
        mLinkCallTask.toStart();
    }

    @Override
    public void BleNotice(byte[] value, int receiveMsg, boolean losePackage) {
        if (!losePackage) {
            switch (receiveMsg) {
                case 0x51:
                    mLinkCallTask.toNext(value);
                    L.i("充值滤芯结果：" + ByteUtils.toHexString(value));
                    break;
                case 0x52:
                    mLinkCallTask.toComplete(value);
                    L.i("反冲洗结果：" + ByteUtils.toHexString(value));
                    break;
            }
        } else {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mLinkCallTask.toRepeat();
                }
            }, 300);
        }
    }


    private void rinseSteps() {
        mLinkCallTask.setNext(new NextInterface() {
            @Override
            public void onNext(Object object) {
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mLinkCallTask.toNext();
                        handler.removeCallbacksAndMessages(null);
                    }
                }, stopTime);
                mHandler = new Handler();
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mDeviceWrite != null) {
                            Toast.makeText(mContext, "设备反冲洗超时", Toast.LENGTH_SHORT).show();
                        }
                        mLinkCallTask.toError();
                        mHandler.removeCallbacksAndMessages(null);
                    }
                }, sameTimeOut);
            }
        }, new NextInterface() {
            @Override
            public void onNext(Object object) {
                if (mDeviceWrite == null) {
                    return;
                }
                String data = DeviceCommand20.getIrrigation("52");
                mDeviceWrite.writeData(data, mMac, null);
                L.i("反冲洗:" + data);
            }
        }).setError(new ErrorInterface() {
            @Override
            public void onError(Object object) {
                if (mLoading != null && mLoading.isShowing()) {
                    mLoading.dismiss();
                }
                Toast.makeText(mContext, "设备反冲洗失败", Toast.LENGTH_SHORT).show();
                mHandler.removeCallbacksAndMessages(null);
                mDeviceNotice.unNotify();//取消监听通知和回调
                mDeviceWrite = null;
                mDeviceNotice = null;
                mDeviceConn = null;
                mContext = null;
            }
        }).setComplete(new CompleteInterface() {
            @Override
            public void onComplete(Object object) {
                if (mLoading != null && mLoading.isShowing()) {
                    mLoading.dismiss();
                }
                byte[] value = (byte[]) object;
                if (ByteParsing.getFilterResetState(value)) {
                    Toast.makeText(mContext, "设备反冲洗成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mContext, "设备反冲洗失败", Toast.LENGTH_SHORT).show();
                }
                mHandler.removeCallbacksAndMessages(null);
                mDeviceNotice.unNotify();//取消监听通知和回调
                mDeviceWrite = null;
                mDeviceNotice = null;
                mDeviceConn = null;
                mContext = null;
            }
        });
    }

    private void ResetFilterSteps() {
        mLinkCallTask.setNext(new NextInterface() {
            @Override
            public void onNext(Object object) {
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mLinkCallTask.toNext();
                        handler.removeCallbacksAndMessages(null);
                    }
                }, stopTime);
                mHandler = new Handler();
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mDeviceWrite != null) {
                            Toast.makeText(mContext, "重置设备滤芯超时", Toast.LENGTH_SHORT).show();
                        }
                        mLinkCallTask.toError();
                        mHandler.removeCallbacksAndMessages(null);
                    }
                }, sameTimeOut);
            }
        }, new NextInterface() {
            @Override
            public void onNext(Object object) {
                if (mDeviceWrite == null) {
                    return;
                }
                String address = "01020" + mResetLevel + "00000000000000";
                String data = DeviceCommand20.getCommand(address, "51");
                mDeviceWrite.writeData(data, mMac, null);
                L.i("复位滤芯:" + data);
            }
        }, new NextInterface() {
            @Override
            public void onNext(Object object) {
                byte[] value = (byte[]) object;
                if (value != null && ByteParsing.getFilterResetState(value)) {
                    String data = DeviceCommand20.getIrrigation("52");
                    mDeviceWrite.writeData(data, mMac, null);
                    L.i("反冲洗:" + data);
                } else {
                    mLinkCallTask.toError();
                }
            }
        }).setError(new ErrorInterface() {
            @Override
            public void onError(Object object) {
                if (mLoading != null && mLoading.isShowing()) {
                    mLoading.dismiss();
                }
                Toast.makeText(mContext, "滤芯重置失败", Toast.LENGTH_SHORT).show();
                mHandler.removeCallbacksAndMessages(null);
                mDeviceNotice.unNotify();//取消监听通知和回调
                mDeviceWrite = null;
                mDeviceNotice = null;
                mDeviceConn = null;
                mContext = null;
            }
        }).setComplete(new CompleteInterface() {
            @Override
            public void onComplete(Object object) {
                if (mLoading != null && mLoading.isShowing()) {
                    mLoading.dismiss();
                }
                byte[] value = (byte[]) object;
                if (ByteParsing.getFilterResetState(value)) {
                    Toast.makeText(mContext, "滤芯重置成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mContext, "滤芯重置失败", Toast.LENGTH_SHORT).show();
                }
                mHandler.removeCallbacksAndMessages(null);
                mDeviceNotice.unNotify();//取消监听通知和回调
                mDeviceWrite = null;
                mDeviceNotice = null;
                mDeviceConn = null;
                mContext = null;
            }
        });
    }

    public void connDev() {
        sameTimeOut = 15000;
        if (mLoading != null && mLoading.isShowing()) {
            mLoading.dismiss();
        }
        final LoadingDialog dialog = new LoadingDialog(mContext, "正在连接设备");
        dialog.show();
        DeviceConn deviceConn = new DeviceConn();
        deviceConn.conn(mMac, new ConnListener() {
            @Override
            public void onConn(int code, BleGattProfile profile) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                if (code == Code.REQUEST_SUCCESS) {
                    stopTime = 1000;
                    start();
                } else if (code == Code.BLUETOOTH_DISABLED) {
                    new AlertDialog.Builder(mContext).
                            setTitle("提示")
                            .setMessage("请开启蓝牙后重试")
                            .setPositiveButton("确定", null).show();
                    mLinkCallTask.toError();
                } else {
                    new AlertDialog.Builder(mContext).
                            setTitle("提示")
                            .setMessage("设备连接错误")
                            .setPositiveButton("确定", null).show();
                    mLinkCallTask.toError();
                }
            }
        });
    }


}
